var express = require('express');
var router = express.Router();
let upload = require('../util/multer/index')
var moment = require('moment');
const rp = require('request-promise-native');
let { getBase64, setBase64, isgender, FormatData } = require('../util.js');
let { GetopenID_Url, appId, AppSecret, INDEX_RECOMMENDNUM, INDEX_HOTRECOMMENDNUM } = require('../config');
let { getSwiperList, getRecommendList, getRticleatypeList, isUser, addUser, updataUser, GetUsersById, getRticleabyType, getMenutypeList,
  getMenuBytype, getMenuByTime, getMenuById, isaddPraise, delPraise, changeMenuPraise, addPraise, isaddRelation, isaaddFollow, delFollow,
  addFollow, getHotRecommendList, getRticleaById, changeRticleaRead, getUserPraiseMenu, getUserFollowMenu, getMenuByName, getMotionList,
  getMenuAll, addPlan, getWeekPlan
} = require('../mysql/users')
/**
 * 所有关于用户的请求接口
 */
const methodsToken = [
  '/userInfoInit',
  '/addPraise',
  '/addFollow',
  '/getUserPraiseMenu',
  '/getUserFollowMenu',
  '/weekPlanArrange',
  '/getWeekPlanArrange'
];
router.post("*", (req, res, next) => {
  // 判断token是否存在
  if (methodsToken.indexOf(req.url) >= 0) {
    // 获取用户token
    let userToken = req.headers.token;
    if (!userToken) {
      return res.json({
        code: 0,
        data: "请先登录"
      });
    } else {
      let userId = setBase64(userToken);
      req.body.userId = userId;
    }
  } else {
    let userToken = req.headers.token;
    if (userToken) {
      let userId = setBase64(userToken);
      req.body.userId = userId;
    }
  }
  next();
})
/**
 *  获取openid
 */
router.post('/login', async (req, res, next) => {
  let url = `${GetopenID_Url}appid=${appId}&secret=${AppSecret}&js_code=${req.body.code}&grant_type=authorization_code`;
  let userCode = await rp({
    method: 'GET', url, json: true
  })
  let isUserInfo = await isUser({
    openid: userCode.openid
  })
  if (isUserInfo.length) {
    res.json({
      code: 1,
      data: {
        Token: getBase64(isUserInfo[0].userId)
      }
    })
  } else {
    let data = await addUser({
      openid: userCode.openid,
      session_key: userCode.session_key
    })
    res.json({
      code: 1,
      data: {
        Token: getBase64(data.insertId)
      }
    })
  }
});
/**
 *   修改初始信息并返回用户信息
 */
router.post('/upinfoLogin', async (req, res, next) => {
  let { nickName, gender, avatarUrl, userId, Token } = req.body;
  userId = setBase64(Token)
  await updataUser(userId, {
    userName: nickName,
    userSex: isgender(gender),
    userUrl: avatarUrl
  })
  let data = await GetUsersById(userId);
  res.json({
    code: 1,
    data
  })
})
/**
 * 同步用户数据
 */
router.post('/userInfoInit', async (req, res, next) => {
  let { nickName, gender, avatarUrl, userId } = req.body;
  await updataUser(userId, {
    userName: nickName,
    userSex: isgender(gender),
    userUrl: avatarUrl
  })
  let data = await GetUsersById(userId);
  res.json({
    code: 1,
    data
  })
})
/**
 * 返回用户信息
 */
router.post('/userInfoById', async (req, res, next) => {
  let { userId } = req.body;
  let data = await GetUsersById(userId);
  res.json({
    code: 1,
    data
  })
})
/**
 * 返回首页轮播图数据
 */
router.get('/getSwiperList', async (req, res, next) => {
  let data = await getSwiperList();
  res.json({
    code: 1,
    data
  })
})
/**
 * 返回首页推荐的菜谱
 */
router.get('/getRecommendList', async (req, res, next) => {
  let data = await getRecommendList(INDEX_RECOMMENDNUM);
  res.json({
    code: 1,
    data: FormatData(data, {
      menuImgList: 'json',
      menuTag: 'json',
      menuDate: 'time'
    })
  })
})
/**
 * 获取热门菜谱
 */
router.get('/getHotRecommendList', async (req, res, next) => {
  let data = await getHotRecommendList(INDEX_HOTRECOMMENDNUM);
  res.json({
    code: 1,
    data: FormatData(data, {
      menuImgList: 'json',
      menuTag: 'json',
      menuDate: 'time'
    })
  })
})
/**
 * 获取文章分类
 */
router.get('/getRticleatypeList', async (req, res, next) => {
  let data = await getRticleatypeList();
  res.json({
    code: 1,
    data
  })
})
/**
 * 获取指定分类的文章
 */
router.post('/getRticleabyType', async (req, res, next) => {
  let { page, limit, rticleaTitle } = req.body;
  var num = (page - 1) * limit;
  let data = await getRticleabyType(num, limit, {
    rticleaType: rticleaTitle
  });
  res.json({
    code: 1,
    data: FormatData(data.data, {
      rticleaImgList: 'json',
      rticleaTime: 'time'
    }),
    count: data.count
  })
})
/**
 * 获取菜谱分类
 */
router.get('/getMenutypeList', async (req, res, next) => {
  let data = await getMenutypeList();
  res.json({
    code: 1,
    data
  })
})
/**
 * 获取指定分类的菜谱信息
 */
router.post('/getMenuBytype', async (req, res, next) => {
  let { menuType } = req.body;
  let data = await getMenuBytype({
    menuType: menuType
  });
  res.json({
    code: 1,
    data: FormatData(data.data, {
      menuImgList: 'json',
      menuTag: 'json',
      menuDate: 'date'
    }),
    count: data.count,
    menuType: menuType
  })
})
/**
 * 根据指定时区获取菜谱信息
 */
router.post('/getMenuByTime', async (req, res, next) => {
  let { menuTime } = req.body;
  let data = await getMenuByTime({
    menuTime: menuTime
  });
  res.json({
    code: 1,
    data: FormatData(data.data, {
      menuImgList: 'json',
      menuTag: 'json',
      menuDate: 'date'
    }),
    count: data.count,
    menuTime: menuTime
  })
})
/**
 * 更具菜谱id获取菜谱信息
 */
router.post('/getMenuById', async (req, res, next) => {
  let { menuId, userId } = req.body;
  let data = await getMenuById(menuId);
  if (userId) {
    let Praise = await isaddPraise({
      userId, menuId
    })
    let Follow = await isaaddFollow({
      userId, menuId
    })
    data.isFabulous = Boolean(Praise.length)
    data.isCollection = Boolean(Follow.length)
  } else {
    data.isFabulous = false
    data.isCollection = false
  }
  res.json({
    code: 1,
    data: FormatData(data, {
      menuImgList: 'json',
      menuTag: 'json',
      menuDate: 'date'
    })
  })
})
/**
 * 菜谱点赞
 */
router.post('/addPraise', async (req, res, next) => {
  let { userId, menuId } = req.body;
  let flog = await isaddPraise({
    userId, menuId
  })
  if (flog.length) {
    await delPraise(flog[0].praiseId)
    await changeMenuPraise({
      PraiseNum: -1,
      menuId
    })
    res.json({
      code: 1,
      data: {
        info: "取消点赞成功",
        flog: 0
      }
    })
  } else {
    await addPraise({
      userId, menuId
    })
    await changeMenuPraise({
      PraiseNum: 1,
      menuId
    })
    res.json({
      code: 1,
      data: {
        info: "点赞成功",
        flog: 0
      }
    })
  }
})
/**
 * 收藏
 */
router.post('/addFollow', async (req, res, next) => {
  let { userId, menuId } = req.body;
  let flog = await isaaddFollow({
    userId, menuId
  })
  if (flog.length) {
    await delFollow(flog[0].followId)
    res.json({
      code: 1,
      data: {
        info: "取消收藏成功",
        flog: 0
      }
    })
  } else {
    await addFollow({
      userId, menuId
    })
    res.json({
      code: 1,
      data: {
        info: "收藏成功",
        flog: 0
      }
    })
  }
})
/**
 * 根据文章id获取指定文章
 */
router.post('/getRticleaById', async (req, res, next) => {
  let { rticleaId } = req.body;
  await changeRticleaRead({
    rticleaRead: 1,
    rticleaId: rticleaId
  })
  let data = await getRticleaById(rticleaId);
  res.json({
    code: 1,
    data: FormatData(data, {
      rticleaImgList: 'json',
      rticleaTime: 'time'
    })
  })
})
/**
 * 获取用户点赞的菜谱
 */
router.post('/getUserPraiseMenu', async (req, res, next) => {
  let { page, limit, userId } = req.body;
  var num = (page - 1) * limit;
  let data = await getUserPraiseMenu(num, limit, {
    userId: userId
  });
  res.json({
    code: 1,
    data: FormatData(data.data, {
      menuImgList: 'json',
      menuTag: 'json',
      menuDate: 'time'
    }),
    count: data.count
  })
})
/**
 * 获取用户收藏的菜谱
 */
router.post('/getUserFollowMenu', async (req, res, next) => {
  let { page, limit, userId } = req.body;
  var num = (page - 1) * limit;
  let data = await getUserFollowMenu(num, limit, {
    userId: userId
  });
  res.json({
    code: 1,
    data: FormatData(data.data, {
      menuImgList: 'json',
      menuTag: 'json',
      menuDate: 'time'
    }),
    count: data.count
  })
})
/**
 * 根据菜谱名称获取菜谱
 */
router.post('/getMenuByName', async (req, res, next) => {
  let { page, limit, menuName } = req.body;
  var num = (page - 1) * limit;
  let data = await getMenuByName(num, limit, {
    menuName: menuName
  });
  res.json({
    code: 1,
    data: FormatData(data.data, {
      menuImgList: 'json',
      menuTag: 'json',
      menuDate: 'time'
    }),
    count: data.count
  })
})
// 获取运动的所有数据
router.post('/getMotionList', async (req, res, next) => {
  let data = await getMotionList()
  res.json({
    code: 1,
    data
  })
})
/**
 * 图片文件上传处理
 */
router.post('/uploadImg', upload.single('file'), async (req, res, next) => {
  let url = `${req.protocol}://${req.headers.host}/${req.file.path}`;
  res.json({
    code: 1,
    url: urlf2z(url)
  })
})
/**
 * 周计划的食谱安排
 */
router.post('/weekPlanArrange', async (req, res, next) => {
  let { motionDataList, Numbervalue, menuFlavor, userId } = req.body
  let menuListData = await getMenuAll()
  menuListData = menuListData.filter(menuItem => {
    return menuItem.menuFlavor == menuFlavor
  })
  motionDataList.forEach(motionItem => {
    motionItem.motion.forEach(dayItem => {
      let list = []
      let menuList = []
      if (dayItem.type == 'breakfast') {
        list = menuListData.filter(menuItem => menuItem.menuTime == '早餐')
      } else if (dayItem.type == 'lunch') {
        list = menuListData.filter(menuItem => menuItem.menuTime == '午餐')
      } else if (dayItem.type == 'dinner') {
        list = menuListData.filter(menuItem => menuItem.menuTime == '晚餐')
      }
      let sumHot = dayItem.motionList.reduce((previousValue, currentValue) => {
        return previousValue + Number(currentValue.motionHot);
      }, 0)
      let sunEnum = 0
      for (const val of list) {
        menuList.push(val)
        sunEnum += val.menuHot
        if (sunEnum >= sumHot) {
          break;
        }
      }
      dayItem.menuList = menuList
    })
  })
  await addPlan({
    userId: userId,
    Numbervalue: Numbervalue,
    menuFlavor: menuFlavor,
    motionDataList: JSON.stringify(motionDataList),
    planDate: motionDataList[0].date
  })
  res.json({
    code: 1,
    data: {
      userId: userId,
      Numbervalue: Numbervalue,
      menuFlavor: menuFlavor,
      motionDataList: motionDataList,
      planDate: motionDataList[0].date
    }
  })
})
/**
 * 周计划输出
 */
router.post('/getWeekPlanArrange', async (req, res, next) => {
  let { userId, planDate } = req.body
  let weekPlan = await getWeekPlan(userId)
  let obj = {}
  obj = weekPlan.find(weekItem => {
    let startWeek = moment(weekItem.planDate, 'YYYY-MM-DD');
    let endWeek = moment(weekItem.planDate, 'YYYY-MM-DD').add(7, 'days');
    return moment(planDate).isBetween(startWeek, endWeek)
  }) || {}
  if (JSON.stringify(obj) == "{}") {
    res.json({
      code: 0,
      data: ''
    })
  } else {
    res.json({
      code: 1,
      data: FormatData(obj, {
        motionDataList: 'json'
      })
    })
  }

})
module.exports = router;
